package com.example.a_java.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.a_java.common.Result;
import com.example.a_java.dto.LendingApplyDTO;
import com.example.a_java.dto.LendingApprovalDTO;
import com.example.a_java.dto.LendingDetailVO;
import com.example.a_java.dto.LendingListDTO;
import com.example.a_java.dto.LendingProcessDTO;
import com.example.a_java.entity.CustAccount;
import com.example.a_java.entity.LoanContract;
import com.example.a_java.entity.LoanDisbursement;
import com.example.a_java.entity.LoanDisbursementApproval;
import com.example.a_java.service.CustAccountService;
import com.example.a_java.service.LoanContractService;
import com.example.a_java.service.LoanDisbursementApprovalService;
import com.example.a_java.service.LoanDisbursementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 放款管理接口控制器
 */
@RestController
@RequestMapping("/api/lending")
public class LendingController {

    @Autowired
    private LoanDisbursementService loanDisbursementService;
    
    @Autowired
    private LoanDisbursementApprovalService loanDisbursementApprovalService;
    
    @Autowired
    private CustAccountService custAccountService;
    
    @Autowired
    private LoanContractService loanContractService;

    /**
     * 获取放款列表
     */
    @GetMapping("/list")
    public Result<IPage<LoanDisbursement>> getLendingList(LendingListDTO queryDTO) {
        IPage<LoanDisbursement> page = loanDisbursementService.getLendingList(queryDTO);
        return Result.success(page);
    }

    /**
     * 获取放款详情
     */
    @GetMapping("/detail/{disbursementId}")
    public Result<LendingDetailVO> getLendingDetail(@PathVariable Long disbursementId) {
        LendingDetailVO detailVO = loanDisbursementService.getLendingDetail(disbursementId);
        if (detailVO == null) {
            return Result.error("放款记录不存在");
        }
        return Result.success(detailVO);
    }

    /**
     * 导出放款列表
     */
    @GetMapping("/export")
    public void exportLendingList(LendingListDTO queryDTO, HttpServletResponse response) {
        loanDisbursementService.exportLendingList(queryDTO, response);
    }

    /**
     * 获取待放款列表
     */
    @GetMapping("/pending")
    public Result<IPage<LoanDisbursement>> getPendingList(
            @RequestParam(required = false) String contractNo,
            @RequestParam(required = false) String loanNo,
            @RequestParam(required = false) String customerName,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        IPage<LoanDisbursement> page = loanDisbursementService.getPendingList(
                contractNo, loanNo, customerName, pageNum, pageSize);
        return Result.success(page);
    }

    /**
     * 提交放款申请
     */
    @PostMapping("/apply")
    public Result<Map<String, Long>> applyLending(@RequestBody LendingApplyDTO applyDTO) {
        // 假设当前用户ID从上下文中获取
        Long userId = 1L; // TODO: 从上下文中获取当前用户ID
        
        try {
            Long disbursementId = loanDisbursementService.applyLending(applyDTO, userId);
            Map<String, Long> result = new HashMap<>();
            result.put("disbursementId", disbursementId);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 放款处理
     */
    @PutMapping("/process")
    public Result<Object> processLending(@RequestBody LendingProcessDTO processDTO) {
        // 假设当前用户ID从上下文中获取
        Long userId = 1L; // TODO: 从上下文中获取当前用户ID
        
        try {
            boolean result = loanDisbursementService.processLending(processDTO, userId);
            if (result) {
                return Result.success("放款处理成功");
            } else {
                return Result.error("放款处理失败");
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取客户账户信息
     */
    @GetMapping("/account/{customerId}")
    public Result<List<CustAccount>> getCustomerAccounts(@PathVariable Long customerId) {
        List<CustAccount> accounts = custAccountService.getAccountsByCustomerId(customerId);
        return Result.success(accounts);
    }

    /**
     * 新增客户账户信息
     */
    @PostMapping("/account")
    public Result<Map<String, Long>> addCustomerAccount(@RequestBody CustAccount account) {
        // 假设当前用户ID从上下文中获取
        Long userId = 1L; // TODO: 从上下文中获取当前用户ID
        
        try {
            account.setCreateBy(userId);
            account.setCreateTime(LocalDateTime.now());
            boolean result = custAccountService.save(account);
            if (result) {
                Map<String, Long> resultMap = new HashMap<>();
                resultMap.put("id", account.getId());
                return Result.success(resultMap);
            } else {
                return Result.error("新增客户账户失败");
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 设置默认账户
     */
    @PutMapping("/account/default/{accountId}")
    public Result<Object> setDefaultAccount(@PathVariable Long accountId, @RequestParam Long customerId) {
        boolean result = custAccountService.setDefault(accountId, customerId);
        if (result) {
            return Result.success("设置默认账户成功");
        } else {
            return Result.error("设置默认账户失败");
        }
    }

    /**
     * 诊断接口 - 检查放款表数据（仅用于开发调试）
     */
    @GetMapping("/check")
    public Result<List<LoanDisbursement>> checkDisbursementData() {
        List<LoanDisbursement> list = loanDisbursementService.list();
        return Result.success(list);
    }
    
    /**
     * 诊断接口 - 查看合同状态
     */
    @GetMapping("/check-contract")
    public Result<String> checkContractStatus(@RequestParam Long contractId) {
        LoanContract contract = loanContractService.getById(contractId);
        if (contract == null) {
            return Result.error("合同不存在");
        }
        
        StringBuilder result = new StringBuilder();
        result.append("合同ID: ").append(contract.getContractId())
              .append(", 合同编号: ").append(contract.getContractNo())
              .append(", 状态: ").append(contract.getContractStatus());
              
        return Result.success(result.toString());
    }
    
    /**
     * 诊断接口 - 手动创建放款记录（仅用于开发测试）
     */
    @PostMapping("/create-test")
    public Result<String> createTestDisbursement(@RequestParam Long contractId) {
        try {
            // 1. 查询合同信息
            LoanContract contract = loanContractService.getById(contractId);
            if (contract == null) {
                return Result.error("合同不存在");
            }
            
            // 2. 创建放款记录
            LoanDisbursement disbursement = new LoanDisbursement();
            disbursement.setContractId(contract.getContractId());
            disbursement.setAmount(contract.getLoanAmount());
            disbursement.setDisburseStatus(10); // 待审核
            disbursement.setCreateTime(LocalDateTime.now());
            disbursement.setRemark("测试创建");
            disbursement.setIsDeleted(0);
            
            // 保存放款记录
            boolean saved = loanDisbursementService.save(disbursement);
            if (saved) {
                return Result.success("测试放款记录创建成功，ID: " + disbursement.getDisbursementId());
            } else {
                return Result.error("测试放款记录创建失败");
            }
        } catch (Exception e) {
            return Result.error("创建测试放款记录异常: " + e.getMessage());
        }
    }
} 
